<template>
  <div class="app-container">
    <div>
      <el-button
        v-hasPermi="['system:add:folder']"
        type="primary"
        size="small"
        @click="showAddFolder">新建文件夹</el-button>
      <el-button type="primary" size="small" @click="showAddFile">新建文件</el-button>
      <!-- <el-button type="primary" size="small">上传文件</el-button> -->
      <el-button type="primary" size="small" @click="deleteFiles">删除</el-button>
      <!-- <el-button type="primary" size="small">设置排序</el-button> -->
      <!-- <el-button type="primary" size="small">查看共享</el-button> -->
      <!-- <el-button type="primary" size="small">其他</el-button> -->
    </div>
    <el-row class="mt10" :gutter="20">
      <!-- 文件夹 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <FolderTree
            :folderOptions="folderOptions"
            @handleNodeClick="handleNodeClick"
            @modifyFolder="modifyFolder"
            @deleteFolder="deleteFolder"></FolderTree>
        </div>
      </el-col>
      <!-- 文件 -->
      <el-col :span="20" :xs="24">
        <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="名称" align="center" prop="name">
            <template slot-scope="scope">
              <div class="file-box"><i :class="`icon-file icon-file-${fmtFileType(scope.row.format)}`"></i>{{scope.row.name}}</div>
            </template>
          </el-table-column>
          <el-table-column label="大小" align="center"  prop="size" />
          <el-table-column label="下载次数" align="center"  prop="times" />
          <el-table-column label="最后更新" align="center" prop="updateTime" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="updateFile(scope.row)">修改</el-button>
              <el-button type="text" @click="downloadFile(scope.row)">下载</el-button>
              <el-button type="text" @click="deleteFile(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>


    <!-- 添加、修改文件夹 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" v-load="loadingFolder" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="上级文件夹" prop="parentId">
          <span v-if="!form.parentId">无</span>
          <treeselect v-else disabled v-model="form.parentId" :options="folderOptions" :normalizer="normalizer"/>
        </el-form-item>
        <el-form-item label="文件夹描述" prop="introduction">
          <el-input type="textarea" v-model="form.introduction" />
        </el-form-item>
        <el-form-item label="授权查看" prop="viewPermissions">
          <el-scrollbar class="input-box" style="height: 40px;">
            <el-tag 
              v-for="(item, index) in selectedUserByView" 
              :key="`view_${item.id}`"
              size="mini"
              closable
              @close="deleteUserByView(index)">{{item.cnName}}</el-tag>
          </el-scrollbar>
          <el-button type="text" class="select-user-btn" icon="el-icon-circle-plus-outline" circle @click="showSelectUser('view')"></el-button>
        </el-form-item>
        <el-form-item label="授权修改" prop="editPermissions">
          <el-scrollbar class="input-box" style="height: 40px;">
            <el-tag 
              v-for="(item, index) in selectedUserByEdit" 
              :key="`view_${item.id}`"
              size="mini"
              closable
              @close="deleteUserByEdit(index)">{{item.cnName}}</el-tag>
          </el-scrollbar>
          <el-button type="text" class="select-user-btn" icon="el-icon-circle-plus-outline" circle @click="showSelectUser('edit')"></el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFolder">确 定</el-button>
        <el-button @click="addFolderCancel">取 消</el-button>
      </div>
    </el-dialog>

    <selectUserComp ref="selectUserComp" @selected="selectedUser"></selectUserComp>
    <!-- 新建文件 -->
    <addFileComp ref="addFileComp" @addSuccess="addFileSuccess"></addFileComp>
    <updateFileComp ref="updateFileComp" @addSuccess="updateFileSuccess"></updateFileComp>
  </div>
</template>

<script>
import { getFolderList, addFolder, folderDetail, modifyFolder, deleteFolder, getFileList, deleteFile, detailFile, downloadFile } from "@/api/folder";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import FolderTree from "./folderTree.vue"

export default {
  components: {
    selectUserComp: () => import('../system/user/selectUserDialog.vue'),
    addFileComp: () => import('./addFileDialog.vue'),
    updateFileComp: () => import('./modifyFileDialog.vue'),
    Treeselect,
    FolderTree,
  },
  data() {
    return {
      treeLoading: true,
      loading: true,
      folderOptions: [],
      loading: false,
      loadingFolder: false,
      queryParams: {
        page: 1,
        size: 10,
      },
      fileList: [],
      title: "",
      curFolder: null,
      fileselection: [],
      open: false,
      permissionType: "",
      form: {},
      selectedUserByView: [],
      selectedUserByEdit: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入文件夹名称", trigger: "blur" }
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" }
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" }
        ]
      },
    }
  },
  created() {
    this.getFolderList();
    this.getFileList();
  },
  methods: {
    // 获取文件夹
    getFolderList() {
      this.treeLoading = true;
      getFolderList().then(response => {
        this.folderOptions = response.data;
        this.treeLoading = false;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.loading = true;
      this.curFolder = data;
      this.getFileList();
      // this.queryParams.deptId = data.id;
      // this.handleQuery();
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 添加文件夹
    showAddFolder() {
      let parentId=0,ancestral=0;
      if(this.curFolder && this.curFolder.id){
        parentId=this.curFolder.id
        ancestral=this.curFolder.ancestral + "," +this.curFolder.id;
      }
      this.form = {
        "name": "", //文件夹名称
        "parentId": parentId, //父文件夹id
        "ancestral": ancestral, //所有层级
        "path": "",
        "introduction": "", //文件夹描述
        "viewPermissions": [], //查看权限
        "editPermissions": [] //编辑权限
      };

      this.open = true;
    },
    // 获取文件列表
    getFileList() {
      if(!this.curFolder || !this.curFolder.id){
        return
      }
      this.loading = true;
      // tansParams(config.params)
      getFileList(this.curFolder.id, this.queryParams).then(res => {
        this.fileList = res.data.data;
      }).finally(() => {
        this.loading = false;
      })
    },
    handleSelectionChange(selection) {
      this.fileselection = selection
    },
    // 添加文件夹
    submitFolder() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            modifyFolder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getFolderList();
            });
          } else {
            addFolder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getFolderList();
            });
          }
        }
      });
    },
    addFolderCancel() {
      this.open = false;
      this.form = {
        "name": "", //文件夹名称
        "parentId": "0", //父文件夹id
        "ancestral": "", //所有层级
        "introduction": "", //文件夹描述
        "viewPermissions": [], //查看权限
        "editPermissions": [] //编辑权限
      };
      this.resetForm("form");
    },
    modifyFolder(data) {
      this.open = true;
      this.loadingFolder = true;
      folderDetail(data.id).then(res => {
        this.form = {
          "id": data.id,
          "name": data.name, //文件夹名称
          "parentId": data.parentId, //父文件夹id
          "ancestral": data.ancestral, //所有层级
          "introduction": data.introduction, //文件夹描述
          "viewPermissions": res.data.viewPermissions.map(item => item.userId), //查看权限
          "editPermissions": res.data.editPermissions.map(item => item.userId) //编辑权限
        };
        this.selectedUserByEdit = res.data.editPermissions.map(item => { return {id: item.userId, cnName:item.cnName} });
        this.selectedUserByView = res.data.viewPermissions.map(item => { return {id: item.userId, cnName:item.cnName} });
      }).finally(() => {
        this.loadingFolder = false;
      })
    },
    // 删除文件夹
    deleteFolder(data) {
      this.$modal.confirm('是否确认删除名称为"' + data.name + '"的文件夹？').then(function() {
        return deleteFolder(data.id);
      }).then(() => {
        this.getFolderList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    showSelectUser(type) {
      this.permissionType = type;
      let values = type == 'edit' ? this.form.editPermissions : this.form.viewPermissions
      this.$refs["selectUserComp"].show(values);
    },
    // 选择用户后的数据
    selectedUser(userIds, obj) {
      if(this.permissionType == "edit") {
        this.form.editPermissions = userIds;
        this.selectedUserByEdit = obj;
      } else {
        this.form.viewPermissions = userIds;
        this.selectedUserByView = obj;
      }
    },
    deleteUserByView(index) {
      this.form.viewPermissions.splice(index, 1);
      this.selectedUserByView.splice(index, 1);
    },
    deleteUserByEdit(index) {
      this.form.editPermissions.splice(index, 1);
      this.selectedUserByEdit.splice(index, 1);
    },
    showAddFile() {
      if (!this.curFolder) {
        return this.$message.error("请选择文件夹");
      }
      this.$refs["addFileComp"].show(this.curFolder);
    },
    addFileSuccess() {
      this.getFileList();
    },
    updateFile(item) {
      if(!item) {
        return ;
      }
      item.folderName = this.curFolder.name;
      item.folderId = this.curFolder.id;
      this.$refs["updateFileComp"].show(item);
    },
    updateFileSuccess() {
      this.getFileList();
    },
    deleteFile(item) {
      const ids = item.id;
      this.$modal.confirm('是否确认删除"' + item.name + '"文件吗？').then(function() {
        return deleteFile(ids);
      }).then(() => {
        this.getFileList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    deleteFiles() {
      if(!this.fileselection.length) {
        return this.$message.error("请选择需要删除的文件");
      }
      let ids = this.fileselection.map(item => item.id);
      this.$modal.confirm('是否确认删除这些文件吗？').then(function() {
        return deleteFile(ids);
      }).then(() => {
        this.getFileList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      this.deleteFile()
    },
    downloadFile(row) {
      this.download('/file/file-download/'+row.id, {}, row.path).then(res => {
        // this.$message.success("下载成功")
      }).finally(() => {
        this.exportLoading = false;
      })
    },
    fmtFileType(type) {
      if (type == 'doc' || type == 'docx') {
        return "word";
      } else if (type == 'pptx') {
        return 'ppt'
      } else if (type == 'xls' || type == 'xlsx') {
        return 'excel'
      }
      return type
    },
    addCancel() {
      
    },
  }
}
</script>
<style lang="scss" scoped>
.input-box {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding:0 10px;

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.select-user-btn {
  position: absolute;
  right: 0px;
  top: 0px;
  font-size: 20px;
}
.el-tag + .el-tag {
  margin-left: 5px;
}
.file-box {
  display: flex;
}
.icon-file {
  display: inline-block;
  width: 21px;
  height: 22px;
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center;
  margin-right: 5px;
}
.icon-file-jpg{
  background-image: url(../../assets/images/folder/jpg.png);
}
.icon-file-png{
  background-image: url(../../assets/images/folder/png.png);
}
.icon-file-pdf{
  background-image: url(../../assets/images/folder/pdf.png);
}
.icon-file-jpg{
  background-image: url(../../assets/images/folder/jpg.png);
}
.icon-file-excel{
  background-image: url(../../assets/images/folder/excel.png);
}
.icon-file-ppt{
  background-image: url(../../assets/images/folder/ppt.png);
}
.icon-file-word{
  background-image: url(../../assets/images/folder/word.png);
}
.icon-file-zip{
  background-image: url(../../assets/images/folder/zip.png);
}
</style>